using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Agriculture.Api.Read.Application.Command;
using Agriculture.Domain;
using Dapper;
using MediatR;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;

namespace Agriculture.Api.Read.Application.Handler
{
    /// <summary>
    /// 退款申请查询命令处理器
    /// </summary>
    public class RefundApplicationQueryHandler : IRequestHandler<RefundApplicationQuery, RefundApplicationQueryResult>
    {
        private readonly IConfiguration _configuration;

        public RefundApplicationQueryHandler(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public async Task<RefundApplicationQueryResult> Handle(RefundApplicationQuery request, CancellationToken cancellationToken)
        {
            var result = new RefundApplicationQueryResult();
            string connectionString = _configuration.GetConnectionString("DefaultConnection");

            using (var connection = new MySqlConnection(connectionString))
            {
                // 构建查询条件
                var conditions = new List<string>();
                var parameters = new DynamicParameters();

                conditions.Add("r.IsDeleted = 0");

                // 用户名称或手机号查询
                if (!string.IsNullOrEmpty(request.UserSearch))
                {
                    conditions.Add("r.UserPhone LIKE @UserSearch");
                    parameters.Add("@UserSearch", $"%{request.UserSearch}%");
                }

                // 申请时间范围查询
                if (request.StartTime.HasValue)
                {
                    conditions.Add("r.CreateTime >= @StartTime");
                    parameters.Add("@StartTime", request.StartTime.Value);
                }

                if (request.EndTime.HasValue)
                {
                    conditions.Add("r.CreateTime <= @EndTime");
                    parameters.Add("@EndTime", request.EndTime.Value.AddDays(1).AddSeconds(-1)); // 结束时间为当天23:59:59
                }

                // 状态查询
                if (request.Status.HasValue && request.Status.Value > 0)
                {
                    // 1：待处理，2：已处理，3：已拒绝
                    int statusCode = 0;
                    switch (request.Status.Value)
                    {
                        case 1:
                            statusCode = 0; // 待处理状态码
                            break;
                        case 2:
                            statusCode = 1; // 已处理状态码
                            break;
                        case 3:
                            statusCode = 2; // 已拒绝状态码
                            break;
                    }

                    conditions.Add("r.Status = @Status");
                    parameters.Add("@Status", statusCode);
                }

                // 构建WHERE子句
                var whereClause = conditions.Count > 0 ? $" WHERE {string.Join(" AND ", conditions)}" : string.Empty;

                // 统计总记录数
                var countSql = @"
                    SELECT COUNT(1) 
                    FROM refundapplicationmodel r" + whereClause;
                
                var totalCount = await connection.ExecuteScalarAsync<int>(countSql, parameters);

                // 计算总页数
                int totalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize);

                // 分页查询数据
                var offset = (request.PageIndex - 1) * request.PageSize;
                var querySql = @"
                    SELECT 
                        *
                    FROM refundapplicationmodel r
                    " + whereClause + @"
                    ORDER BY r.CreateTime DESC
                    LIMIT @Offset, @PageSize";

                parameters.Add("@Offset", offset);
                parameters.Add("@PageSize", request.PageSize);

                var refundApplications = await connection.QueryAsync<dynamic>(querySql, parameters);

                // 转换为DTO
                var dtoList = refundApplications.Select(r => new RefundApplicationDto
                {
                    ServiceNo = r.ServiceNo,
                    UserPhone = r.UserPhone,
                    RefundAmount = r.RefundAmount,
                    Source = r.Source,
                    CreateTime = r.CreateTime != null ? r.CreateTime : DateTime.Now,
                    ProcessTime = r.ProcessTime,
                    Status = ConvertStatus(r.Status),
                    OrderId = r.OrderId,
                    OrderNo = r.OrderNo
                }).ToList();

                // 构建结果
                result.TotalCount = totalCount;
                result.TotalPages = totalPages;
                result.CurrentPage = request.PageIndex;
                result.RefundApplications = dtoList;
            }

            return result;
        }

        /// <summary>
        /// 转换状态码为状态文本
        /// </summary>
        private string ConvertStatus(int status)
        {
            switch (status)
            {
                case 0:
                    return "待处理";
                case 1:
                    return "已处理";
                case 2:
                    return "已拒绝";
                default:
                    return "未知";
            }
        }
    }
} 